/**
 * Created by sa on 2016/9/22.
 */


var fs = require('fs');

var casper = require('casper').create({
  pageSettings: {
    loadImages: true,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
  },
  logLevel: "debug",//日志等级
  verbose: true,    // 记录日志到控制台
  timeout: 60000,//60秒超时，退出
});

casper.viewport(1024, 1024);

var url = "http://www.httpuseragent.org/"; //casper.cli.raw.get('url');

//排除不相关的请求，加快页面加载进度
casper.on('resource.requested', function (requestData, request) {
  if (requestData.url.indexOf('google-analytics.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('googlesyndication.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('hm.baidu.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('baidustatic.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('share.baidu.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('cbjs.baidu.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('jiathis.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('.cnzz.com') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('.51.la') > 0) {
    request.abort();
  }
  if (requestData.url.indexOf('.tanx.com') > 0) {
    request.abort();
  }
  //this.echo("==============>page.resource.requested"+requestData.url);
});

//超时执行的函数，记录到日志文件
casper.on('timeout', function () {
  //this.echo("===>timeout"+url);
  var fileName = this.evaluate(getFileName);
  var nowTime = this.evaluate(CurentTime);
  fs.write("log/timeout_" + fileName + ".txt", nowTime + "====>" + url + "\r\n", 'a');
});

//请求页面
casper.start(url, function () {
  var status = this.status().currentHTTPStatus;
  var pathP = 'loadTest' + new Date().valueOf() + '.png'
  this.captureSelector(pathP, 'body');
  //fs.write("temp.html", this.getHTML(), 'w');
});


function getFileName() {
  var now = new Date();

  var year = now.getFullYear();       //年
  var month = now.getMonth() + 1;     //月
  var day = now.getDate();            //日
  return (year + "" + month + "" + day);
}

function CurentTime() {
  var now = new Date();

  var year = now.getFullYear();       //年
  var month = now.getMonth() + 1;     //月
  var day = now.getDate();            //日
  var hh = now.getHours();            //时
  var mm = now.getMinutes();          //分

  var clock = year + "-";
  if (month < 10)
    clock += "0";
  clock += month + "-";
  if (day < 10)
    clock += "0";
  clock += day + " ";
  if (hh < 10)
    clock += "0";
  clock += hh + ":";
  if (mm < 10) clock += '0';
  clock += mm;
  return (clock);
}

casper.run();
